<template>
  <div class="container pisa">
    <div class="text-center upload-box">
      <div class="upload-file">
        <el-upload ref="rebateUpload"
          class="upload-demo" 
          drag
          :action="upload" name="excel" :limit="1"
          :before-upload="beforeUpload"
          :headers="headerUpload"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :show-file-list="false"
          :on-error="handleError"
          :on-progress="uploadProcess"
          v-show="isShowUpload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            {{$t('page.drop')}}，
            <em>{{$t('page.click')}}</em>
          </div>
        </el-upload>
        <div class="upload-name-box" v-show="isShowUploadtxt">
          <div class="reset-back" v-if="editText">
            <div
              class="link"
              @click="changLogData">
              {{$t('page.modData')}}
            </div>
            <span class="link"
              @click="handleRemove">{{$t('page.emptyData')}}
            </span>
          </div>
          <div class="upload-name">
            {{uploadFile.name}}
            <span @click="handleRemove">x</span>
          </div>
          <el-progress
            :percentage="retunProces(percentage)"
            :color="customColor"
            v-show="isShowPer">
          </el-progress>
        </div>
      </div>
    </div>
    <!-- 上传done -->

    <div class="container-body"
      v-show="isShowLog">
      <div style="width:60%;float:left;" v-for="item in stepOneList.imgs">
        <img :src="item" alt=""
          style="margin-bottom:30px;width:100%;">
      </div>
      <div
        style="width:40%;float:left;padding-left:50px">
        <div style="text-align:right;margin: -20px 0 20px;">
          <el-button type="text"
            @click="downloadExl()" size="mini">
            {{$t('page.exportTable')}}</el-button>
        </div>
        <table id="table-2" width="100%">
          <tr>
            <td width="50%">
              {{$t('page.formula')}}
            </td>
            <td v-for="item in stepOneList.formulas">
              {{item}}
            </td>
          </tr>
          <tr
            v-if="stepOneList.struct && stepOneList.struct.rsquare">
            <td width="50%">
              {{$t('page.Rsquare')}}
            </td>
            <td>
              {{stepOneList.struct.rsquare}}
            </td>
          </tr>
          <tr v-if="stepOneList.params">
            <td width="50%">
              {{$t('page.parameter')}}</td>
            <td>
              <template
                v-for="(value, key, index) in stepOneList.params[0]">
                <p class="data-item">
                  {{key}}：{{value}} <br> </p>
              </template>
            </td>
          </tr>

          <tr v-if="!stepOneList.exportConcentration">
            <td width="50%">
              {{$t('page.ConcentrationValue')}}
            </td>
            <td>
              <template
                v-for="(value, key) in stepOneList.ndResult">
                <p class="data-item">
                  {{key}}：{{value}}
                  <br>
                </p>
              </template>
            </td>
          </tr>
        </table>
      </div>
      <!-- 96孔 -->
      <div style="padding-left:40px;">
        <holesTable 
          v-if="stepOneList.exportConcentration"
          :noDisabled="data.Odname"
          @inputHoles="inputHoles"
          :unKnowResult="stepOneList.unKnowResult"
          :exportConcentration="stepOneList.exportConcentration_multiple">
        </holesTable>

        <!-- <histogram
          v-if="isShowLog"
          :data="stepOneList.histogram"
        ></histogram> -->
      </div>
    </div>

    <!-- 提交弹窗 -->
    <el-dialog :visible="isShowStepOne"
      :close-on-click-modal="false"
      :show-close="false" 
      :destroy-on-close="true"
      @open="handlerOpen"
      width="80%">
      <el-form 
        label-position="right"
        label-width="100px">
        <el-form-item :label="$t('page.unit')">
          <el-checkbox-group v-model="unit">
            <el-checkbox 
              v-for="(item, index) in unitList"
              :key="index" 
              v-model="unit" 
              :label="item"
            ></el-checkbox>
          </el-checkbox-group>
          <!-- <el-radio
            v-for="(item, index) in unitList"
            :key="index" 
            v-model="unit"
            :label="item">{{item}}</el-radio> -->
        </el-form-item>
        <el-form-item class="formItemHole" :label="$t('page.holeName')">
          <h4 class="holeName-text">{{$t('page.multiple')}}</h4>
          <table id="table-1" v-if="data && data.Odname">
            <tr>
              <td 
                v-for="(table,index) in data.Odname"
                :key="index"
                width="100">
                {{index+1}}
              </td>
            </tr>
            <tr>
              <td 
                v-for="(table,index) in data.Odname"
                :key="index">
                <span v-if="typeof multipleList[index] === 'object'" class="flex">
                  <span>已填写 </span>
                  <span class="x_icon" @click="delBtn(index)">X</span>
                </span>
                <el-input
                  v-else
                  clearable
                  v-model="multipleList[index]"></el-input>
              </td>
            </tr>
          </table>
        </el-form-item>
        <el-form-item :label="$t('page.fillInformation')">
          <!-- 填写信息 -->
          <div class="flex">
            <el-select 
              style="margin-right: 20px;"
              v-model="informationItem">
              <el-option
                v-for="item in noMultipleList"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-button 
              :disabled="Boolean(!informationItem)"
              type="primary" 
              @click="informationVisible = true"
            >{{$t('public.comfirmText')}}</el-button>
          </div>
        </el-form-item>
        <!-- 标曲 -->
        <el-form-item class="formItemHole" :label="$t('page.scalarArray')">
          <h4 class="holeName-text" style="left: 30px;">{{$t('page.cutoffCoefficient')}}</h4>
          <table id="table-1">
            <tr>
              <td 
                v-for="(table,index) in 12"
                :key="index">
                <el-input
                  clearable
                  v-model="standardSong[index]"></el-input>
              </td>
            </tr>
            <tr>
              <td 
                v-for="(table,index) in 12"
                :key="index">
                <el-input
                  clearable
                  v-model="cutoffValue[index]"></el-input>
              </td>
            </tr>
          </table>
        </el-form-item>
        <el-form-item :label="$t('page.label')">
          <holesTable 
            :noDisabled="data.Odname"
            :clear.sync="clear"
            @inputHoles="inputHoles"
          ></holesTable>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handlerClose">
          {{$t('page.cancel')}}</el-button>
        <el-button type="primary"
          :loading="btnLoading" @click="submit">
          {{$t('public.comfirmText')}}
        </el-button>
      </span>
    </el-dialog>

    <!-- 填写信息弹窗 -->
    <el-dialog
      :title="$t('page.fillInformation')"
      :visible.sync="informationVisible"
      width="50%">
      <el-form ref="form" :model="infoForm" label-width="80px">
        <el-form-item :label="$t('page.number')">
          <el-input v-model="infoForm.number"></el-input>
        </el-form-item>
        <el-form-item :label="$t('public.name')">
          <el-input v-model="infoForm.name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('public.age')">
          <el-input v-model="infoForm.age"></el-input>
        </el-form-item>
        <el-form-item :label="$t('public.sex')">
          <el-select v-model="infoForm.sex">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
          :label="$t('page.holeName')" 
          v-if="data && data.Odname">
          <el-select v-model="infoForm.holeName">
            <el-option
              v-for="item, index in data.Odname"
              :key="index"
              :label="item" 
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="informationCanle">{{$t('public.cancel')}}</el-button>
        <el-button 
          type="primary" 
          @click="handlerInformation"
        >{{$t('public.comfirmText')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import easyChart from "@/components/EasyChart";
import { pisaOnestep2 } from "@/api/table";
import { setStore, getStore } from "@/utils/common";
import { getToken, removeToken } from "@/utils/auth";
import holesTable from "@/components/96HolesTable";
// import histogram from '../components/histogram.vue'

import _ from 'lodash'
export default {
  data() {
    return {
      stepOneList: {
        params: {},
        struct: {},
        ng: [],
        x: "",
        histogram: {}
      },
      unitList: ["mg/ml", "pg/ml", "ng/ml", "μg/ml", "gc/ml"],
      multipleList: [],  // 倍数填写数据
      standardSong: [], // 标曲
      noMultipleList: [],  // 没填写倍数
      informationItem: '',  // 选择的key
      informationVisible: false,  // 填写信息弹窗
      infoForm: {
        name: '',
        number: '',
        sex: '',
        age: '',
        holeName: '',
      },
      holeList: [],
      concentration: [], // 输入的浓度
      cutoffValue: [], 
      isShowLog: false, //是否结果页面
      isShowStepOne: false, //是否显示弹窗
      isShowUpload: true, // 上传组件
      isShowUploadtxt: false, // 文件名
      uploadFile: {}, // 上传的文件
      exlName: "", // 下载表格名
      isShowPer: false, // 进度条
      percentage: 0, // 进度条数值
      customColor: "#e6a23c",
      unit: ["μg/ml"], // 单位
      data: {}, // 文件上传返回的数据
      btnLoading: false, // 按钮loading
      editText: false, // 兼容老页面不展示修改数据按钮
      clear: false, //清空数据
    };
  },
  components: {
    easyChart,
    holesTable,
    // histogram,
  },
  methods: {
    initData() {},
    changLogData() {
      this.isShowStepOne = true
      // this.clear = true
    },
    goNext(route, type) {
      if (type === 1) {
        setStore("chartData", this.lightRate);
      }
      this.$router.push({ path: route });
    },

    // 删除某个 已填写的信息
    delBtn(i) {
      this.$set(this.multipleList, i, '')
    },

    // 提交个人信息
    handlerInformation() {
      const obj = _.cloneDeep(this.infoForm)
      this.$set(this.multipleList, (this.informationItem-1), obj)
      // this.multipleList[this.informationItem - 1] = this.infoForm
      this.informationVisible = false
      this.informationItem = ''
    },

    // 取消时清空信息
    informationCanle() {
      for (const k in this.infoForm) {
        this.infoForm[k] = ''
      }
      this.informationVisible = false
    },

    inputHoles(value) {
      this.concentration = value;
    },
    handlerOpen() {
      this.$nextTick(() => {
        this.multipleList = []
        this.selectedList(this.multipleList)
      })
    },

    // 关闭弹窗
    handlerClose() {
      this.isShowStepOne = false;
      this.concentration = [];
    },

    // 弹窗提交信息
    async submit() {
      this.btnLoading = true;
      this.data.Odname.forEach((item, index) => {
        this.concentration[index] =
          this.concentration[index] || 0 ? this.concentration[index] : "";
      });

      const userList = this.multipleList.filter(item => typeof item === 'object')
      try {
        const res = await pisaOnestep2({
          concent: this.concentration,
          units: this.unit,
          uuid: this.exlName,
          cutoffs: this.cutoffValue.filter(Boolean),
          bqName: this.standardSong.filter(Boolean),
          userList: userList.map(item => {
            return {
              label: item.number,
              name: item.name,
              sex: item.sex,
              age: item.age,
              key: item.holeName
            }
          }),
          multiple: this.multipleList.filter(item => {
            return typeof item !== 'object' && item >= 0
          })
        });
        if (res.status === 200) {
          this.isShowStepOne = false;
          this.isShowLog = true;
          this.btnLoading = false;
          this.stepOneList = res.data;
        }
      } catch {
        return (this.btnLoading = false);
      }
    },

    beforeUpload(file) {
      this.uploadFile = file;
      this.isShowPer = true;
      this.isShowUpload = false;
      this.isShowUploadtxt = true;
      this.percentage += 60 + Math.floor(Math.random() * 10);
    },
    uploadProcess(e, file, fileList) {
      this.uploadFile = file;
      this.percentage = 100;
    },
    retunProces(num) {
      return Number(num.toFixed(0));
    },
    handleSuccess(file, filelist) {
      if (file.status === 200) {
        if (file.data.img) {
          this.stepOneList = file.data;
          this.isShowLog = true;
          this.isShowPer = false;
          return;
        }
        this.editText = true
        this.data = file.data;
        console.log(this.data);
        this.isShowPer = false;
        this.isShowStepOne = true;
        this.clear = true
        this.exlName = file.data.uuid;
        this.holeList = file.data.Odname
        setStore('auuid', file.data.uuid)
      } else {
        if (file.status === 502) {
          this.$msgbox
            .confirm(
              "你已被登出，可以取消继续留在该页面，或者重新登录",
              "确定登出",
              {
                confirmButtonText: "重新登录",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
            .then(() => {
              store.dispatch("FedLogOut").then(() => {
                location.reload();
              });
            });
        } else {
          this.$message.error(file.msg);
        }
      }
    },
    handleError() {
      this.$message.error("发生错误请联系管理员");
    },
    logout() {
      removeToken();
      this.$router.go("/");
    },
    handleRemove() {
      this.$refs["rebateUpload"].clearFiles(); //清除文件
      //上传框
      this.isShowUpload = true;
      this.isShowUploadtxt = false;
      //上传进度条
      this.percentage = 0;
      //显示进度
      this.isShowPer = false;
      this.stepOneList = {
        params: {},
        struct: {},
        ng: "",
        x: "",
      };
      this.cutoffValue = []
      this.standardSong = [], // 标曲
      this.multipleList = [],  // 倍数填写数据
      this.noMultipleList = [], 
      this.uploadFile = {};
      this.data = {}
      this.isShowStepOne = false;
      this.isShowLog = false;
      this.editText = false
      // this.concentration = [];
      // this.clear = true
    },
    downloadExl() {
      if (this.exlName) {
        const lang = getStore("spr-lang");
        const href = `${process.env.BASE_URL}receive/download/excel/1/${lang}/${this.stepOneList.uuid}`;
        window.open(href, "_blank");
      }
    },
    selectedList(value) {
      this.noMultipleList = []
      const num = this.data && this.data.Odname?.length
      for (let i = 0; i < num; i++) {
        this.noMultipleList.push( value[i] || '' );
      }
      this.noMultipleList = this.noMultipleList.map((item, index) => !item && item !== '0' ? index + 1 : '' ).filter(Boolean)
    }
  },
  computed: {
    upload: () => {
      return process.env.BASE_URL + "pisatwo/upload/pisa/step1";
    },
    headerUpload: () => {
      const data = {};
      data.TOKEN = getToken();
      if (localStorage.getItem("spr-lang") === "en") {
        data.LANG = "ENG"; // 传语言
      }
      return data;
    },
  },
  watch: {
    // 监听填写倍数数组，获取填写信息列表
    multipleList: {
      handler(value) {
        this.selectedList(value)
      },
      deep: true,
      immediate: true
    },
  }
};
</script>
<style lang="less" scoped>
.pisa {
  ::v-deep {
    .el-form-item__label::before {
      content: '*';
      color: red;
      margin-right: 2px;
    }
  }
  .holeName-text::before {
    content: '*';
    color: red;
    margin-right: 2px;
  }
  .x_icon {
    display: inline-block;
    width: 20px;
    height: 20px;
    border-radius: 10px;
    background-color: #409eff;
    color: #fff;
    cursor: pointer;
    line-height: 20px;
  }
  .upload-name {
    display: flex;
    align-items: center;
    width: 100%;
    span {
      margin-left: 4px;
    }
  }
  #table-1 {
    td {
      min-width: 120px;
    }
  }
  .form-item {
    position: relative;
  }
  .concent {
    position: absolute;
    top: 70px;
    left: 40px;
    font-weight: 700;
  }
  ::v-deep {
    .el-dialog__footer {
      text-align: center;
    }
    .el-form-item__content {
      overflow: auto;
      position: static;
    }
  }
  .formItemHole {
    position: relative;
    .holeName-text {
      position: absolute;
      top: 50px;
      left: 60px;
    }
  }
  table {
    width: 100%;
    border-collapse: collapse;
    text-align: center;
    margin-bottom: 20px;
  }
  #table-2 {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: #000;
  }
  #table-2 tr {
    border: 1px solid #000 !important;
  }

  #table-2 td:first-child {
    border-left: 1px solid #000;
  }

  /* Padding and font style */
  #table-2 td,
  #table-2 th {
    min-width: 80px !important;
    padding: 10px 15px;
    font-size: 12px;
    font-family: Verdana;
    border-right-width: 1px;
    border-right-style: solid;
  }

  .reset-back {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .link {
      width: 100px;
      cursor: pointer;
      color: #409eff;
      font-style: normal;
      margin-right: 20px;
    }
  }

  .data-item {
    text-align: left;
    padding-left: 40px;
  }

  // @media screen and (min-width: 1000px) {
  //   .data-item {
  //     display: inline-block;
  //     margin-right: 20px;
  //   }
  // }
}
</style>